<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Chart extends MY_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper('string_helper');
        
        $this->load->model('tree_model');
        $this->load->model('bookmarks_model');
        $this->load->model('user_profiles');
        $this->load->model('search_model');
        $this->load->model('chart_model');
        $this->load->model('role_model');
        $this->load->model('setting_model','settings');
    }

    public function index()
    {
        redirect('/');
    }
    
    public function node(){
        
        $node_hash = $this->uri->segment(3);
        $onlychild = ($this->uri->segment(4) == "onlychild");
        
        $charts_ary = $this->tree_model->get_list_nodes($node_hash,$onlychild);
        
        $data['content']     = $this->get_content($charts_ary);
        
        $this->make_content($data);
    }

    /**!!!
     * на Входе массив обьектов
     * @param array $charts_arr objects
     * @return string
     */
    private function get_content($charts_arr){
        $this->settings->validate_cookie();
        
        $content = "\n";
        $perms = $this->role_model->get_permissions($this->session->userdata('role'));
        $bookmarks = $this->bookmarks_model->get_list_bookmarks();
        $force_not_preview = ((count($charts_arr) == 1) && (count($this->settings->get_chart_periods()) < 2)); //?true:false;
        
        foreach ($charts_arr as $chart_obj){
            if($this->role_model->is_allow_node_rev($chart_obj,$perms)){
                //проверка на доступ по дате
                $date_access = !empty($_GET['formdate'])?replace_quotes($_GET['formdate']):date("j.m.y");
        
                if($this->role_model->access_chart_by_date($date_access)){
                    //if($this->session->userdata('role') != $this->config->item('admin_role_id'))
					if(!$this->role_model->isAdminRole())
                        $this->settings->write_to_log($chart_obj->get_hash()."\t".$chart_obj->get_title_full());
                    
                    $content .= $this->get_image($chart_obj, replace_quotes($_SERVER['QUERY_STRING']), $force_not_preview, array_key_exists($chart_obj->get_hash(), $bookmarks));
                    $content .= "\n";

                }else{
                    //if($this->session->userdata('role') != $this->config->item('admin_role_id'))
                    if(!$this->role_model->isAdminRole())
                        $this->settings->write_to_log("Data not view! date wrong \t".$chart_obj->get_hash()."\t".$chart_obj->get_title_full());
                    $content .= sprintf("<h4>%s</h4>%s<br><br>\n",$chart_obj->get_title_full(),$this->config->item('string_no_data_chart'));
                }
            }else{
                if(count($charts_arr) == 1){
                    //if($this->session->userdata('role') != $this->config->item('admin_role_id'))
                    if(!$this->role_model->isAdminRole())
                        $this->settings->write_to_log("Access Denied!\t".$chart_obj->get_hash()."\t".$chart_obj->get_title_full());
                    $content .= sprintf("<h4>%s</h4>%s<br><br>\n",$chart_obj->get_title_full(),$this->config->item('string_access_denied_node'));
                }
            }
        }
        return $content;
    }

   
    private function get_image($node_obj, $query, $force_not_preview, $has_bookmark=FALSE){
        $use_preview = $this->settings->get_chart_use_preview();
        if($force_not_preview) $use_preview = false;

        $valign = $use_preview || strstr($this->settings->get_chart_mode(),'--no-legend')?'':'style="vertical-align: top;"';
        $res = "<div class='chartcell' ".$valign.">";
        $periods = $this->settings->get_chart_periods();

        $atitle = $force_not_preview?$node_obj->get_title_full():"<a href='/chart/node/".$node_obj->get_hash()."' class='atitle'>".$node_obj->get_title_full()."</a>";
        
        if($has_bookmark){
            $imgBook = '';
        }else{
            $imgBook = '<img align="bottom" id="bkm'.$node_obj->get_hash().'" class="fav hand" title="Добавить в закладки" alt="Добавить в закладки" src="/images/star-small.gif"> ';
        }
        
        $desc = $this->chart_model->get_description($node_obj);
//        $desc_tooltip = $desc === FALSE ? "" : sprintf(' <img data-tooltip="%s" align="bottom" class="" title="Описание" alt="Описание" src="%s" /> ',$desc,  $this->config->item('desc_chart_image'));
        $desc_tooltip = $desc === FALSE ? "" : sprintf(' <img data-toggle="popover" data-trigger="focus" data-placement="bottom" data-content="%s" align="bottom" class="cur-help" title="Описание" alt="Описание" src="%s" /> ',$desc,  $this->config->item('desc_chart_image'));

        $atitle = $imgBook . $atitle . $desc_tooltip;
        
        if(count($periods) < 2){
            $width_title = $use_preview?$this->settings->get_chart_width_preview():$this->settings->get_chart_width();
            $res .="<div style='width:{$width_title}px;'><h4>$atitle</h4></div>\n";
        }else{
            $res .="<h4>$atitle</h4>\n";
        }

        $ctime = 'ctime='.time();

        if ($query == '') {
            foreach ($periods as $value) {
                $query = (0 === $value) ? "" : "formperiod={$value}&";

                if ($use_preview) {
                    $res .= sprintf(' <a href="/chart/image/%1$s?%4$s%3$s" title="%2$s" class="lbox"><img src="%5$s" alt="%2$s" title="%2$s" border="0"></a>',
                            $node_obj->get_hash(), 
                            $node_obj->get_title_full(), 
                            $ctime, 
                            $query, 
                            (stristr($_SERVER['HTTP_USER_AGENT'], 'MSIE') ? '/chart/imagepreview/' . $node_obj->get_hash() : $this->imagepreviewbase64($node_obj->get_path())));
                }else{
                    $res .= sprintf(' <img src="/chart/image/%1$s?%4$s%3$s" alt="%2$s" title="%2$s">', 
                            $node_obj->get_hash(), 
                            $node_obj->get_title_full(), 
                            $ctime, 
                            $query);
                }
            }
        }else {
            if($use_preview){
                $res .= sprintf(' <a href="/chart/image/%1$s?%4$s&%3$s" title="%2$s" class="lbox"><img src="%5$s" alt="%2$s" title="%2$s" border="0"></a>',
                        $node_obj->get_hash(), 
                        $node_obj->get_title_full(), 
                        $ctime, 
                        $query, 
                        stristr($_SERVER['HTTP_USER_AGENT'], 'MSIE') ? "/chart/imagepreview/{$node_obj->get_hash()}?$query&$ctime" : $this->imagepreviewbase64($node_obj->get_path()));
            }else{
                $res .= sprintf(' <img src="/chart/image/%1$s?%4$s&%3$s" alt="%2$s" title="%2$s">', 
                        $node_obj->get_hash(), 
                        $node_obj->get_title_full(), 
                        $ctime, 
                        $query);
            }

        }

       return $res.'</div>';
    }
    
    public function image(){
        header('Content-type: image/png');
        $node_obj = $this->node_model->get_node($this->uri->segment(3));
        
        $cmd = sprintf('%s "%s" - %s %s " %s" %s %s %s "%s"',
                $node_obj->get_path(), 
                $this->chart_model->opt_date_graph(), 
                $this->chart_model->opt_start_time(), 
                $this->chart_model->opt_end_time(),
                $this->chart_model->opt_title_date($node_obj->get_path()), 
                $this->chart_model->opt_width(), 
                $this->chart_model->opt_height(), 
                $this->chart_model->opt_x_grid(), 
                $this->chart_model->opt_mode());
//        $cmd = $path.' "'.$this->graph_opt('date_graph').'" - '.$this->graph_opt('starttime').' '.$this->graph_opt('endtime').' " '.$this->graph_opt('titledate',$path).'" '.$this->graph_opt('width').' '.$this->graph_opt('height').' '.$this->graph_opt('xgrid').' "'.$this->graph_opt('mode').'"';
        echo shell_exec($cmd);
//        echo $cmd;
//        echo file_get_contents('c:\server\sites\vas2.local\images\chart.png');
    }
    
    private function imagepreviewbase64($node_path){
        if(strripos($this->chart_model->opt_mode(), "--no-legend") === false){
            $mode = $this->chart_model->opt_mode()." --no-legend";
        }else{
            $mode = $this->chart_model->opt_mode();
        }
        
        $width = $this->settings->get_chart_width_preview();
        $height= $this->settings->get_chart_height_preview();
        
        $cmd = sprintf('%s "%s" - %s %s " %s" %s %s %s "%s"',
                $node_path,
                $this->chart_model->opt_date_graph(),
                $this->chart_model->opt_start_time(),
                $this->chart_model->opt_end_time(),
                $this->chart_model->opt_title_date($node_path),
                $width,
                $height,
                $this->chart_model->opt_x_grid(TRUE),
                $mode);
//        $cmd = $path.' "'.$this->graph_opt('date_graph').'" - '.$this->graph_opt('starttime').' '.$this->graph_opt('endtime').' " '.$this->graph_opt('titledate',$path).'" '.$width.' '.$height.' '.$this->settings->get_chart_xgrid_param($this->graph_opt('period'),TRUE).' "'.$mode.'"';  //--no-legend
        
        $data = shell_exec($cmd);
        $base64 = 'data:image/png;base64,' . base64_encode($data);
        return $base64;
    }

    public function imagepreview(){
        header('Content-type: image/png');
        $width = $this->settings->get_chart_width_preview();
        $height= $this->settings->get_chart_height_preview();
        
        $node_obj = $this->node_model->get_node($this->uri->segment(3));

        if(strripos($this->graph_opt('mode'), "--no-legend") === false){
            $mode = $this->graph_opt('mode')." --no-legend";
        }else{
            $mode = $this->graph_opt('mode');
        }
        $cmd = sprintf('%s "%s" - %s %s " %s" %s %s %s "%s"',
                $node_obj->get_path(), 
                $this->chart_model->opt_date_graph(), 
                $this->chart_model->opt_start_time(), 
                $this->chart_model->opt_end_time(),
                $this->chart_model->opt_title_date($node_obj->get_path()), 
                $width, 
                $height, 
                $this->chart_model->opt_x_grid(TRUE), 
                $this->chart_model->opt_mode());
//        $cmd = $path.' "'.$this->graph_opt('date_graph').'" - '.$this->graph_opt('starttime').' '.$this->graph_opt('endtime').' " '.$this->graph_opt('titledate',$path).'" '.$width.' '.$height.' '.$this->settings->get_chart_xgrid_param($this->graph_opt('period'),TRUE).' "'.$mode.'"';  //--no-legend
//        echo rtrim($cmd) . "\n<br>";
        
        echo shell_exec($cmd);
    }

    public function bookmark(){
        $node_hash = $this->uri->segment(3);
        if('fld' == $node_hash){
            $is_folder = TRUE;
            $node_hash = $this->uri->segment(4);
        }else{
            $is_folder = FALSE;
        } 

        $charts_arr = $this->bookmarks_model->get_list_charts($node_hash,$is_folder); 
        $data['content'] = $this->get_content($charts_arr);
        $this->make_content($data);
    }
    
    private function make_content($data){
        $data['title']          = "Статистика (".$this->session->userdata['login'].")";
        $data['user_name']      = $this->session->userdata['login'];
//        $data['reload_period']  = empty($_GET['formdate'])?$this->setting_model->get_chart_reload():(int)86400;
        $data['reload_period']  = (filter_input(INPUT_GET, 'formdate', FILTER_NULL_ON_FAILURE) !== null)?$this->setting_model->get_chart_reload():(int)86400;

        $data['chart_width'] = $this->chart_model->opt_width();
        $data['chart_height']= $this->chart_model->opt_height();
        $data['chart_date']  = date("d.m.Y",$this->chart_model->opt_start_time());
        
        $data['settings'] = $this->setting_model->get_settings();
        
        $this->load->view('ver2/charts_view',$data);
    }
    
    public function search(){
        //if($this->session->userdata('role') != $this->config->item('admin_role_id') || $this->session->userdata('logged_in') != TRUE){
        if(!$this->role_model->isAdminRole()){
            redirect('/');
            exit();
        }
        $serch_word = $this->uri->segment(3,'');
        
        $charts_arr = $this->search_model->get_ary_for_charts($serch_word);
        $data['content'] = $this->get_content($charts_arr);
        
        $this->make_content($data);
//        exit();
//        $data['title']          = "Статистика (".$this->session->userdata['login'].")";
//        $data['content_view']   = 'content_view';
//        $data['user_name']      = $this->session->userdata['login'];

        


//        $data['chart_width'] = $this->chart_model->opt_width();
//        $data['chart_height']= $this->chart_model->opt_height();
//        $data['chart_date']  = date("d.m.Y",$this->chart_model->opt_start_time());
//
//        $this->load->view('ver2/charts_view',$data);
    }

}
